/**
 * 佣金管理
 */
define(function(require, exports, module) {
    var angular = require("angular");
    var moment = require("moment");
    var _ = require("underscore");
    var util = require("util");
    var $ = require("jquery");

    var commonModule = angular.module('commonModule', ['ngUI', 'ngInterceptor']);

    function baseDataService($http, $q) {
        var service = {
            // 选定的项目 ID
            //projectIds: [],
            // 项目列表
            //projectList: [],
            // 客户确认模式
            khmode: 1,
            // 默认周期
            defaultCycle: '1',
            // 开始时间
            startDate: '',
            // 结束时间
            endDate: '',
            // 允许周期按周显示
            allowWeekCycle: false,
            // 允许周期按月显示
            allowMonthCycle: false,
            // 需要项目列表
            showProjectList: true,
            // 全局颜色
            colorArray: [
                '#FEC418', '#3DDAC9', '#41C3EE', '#FF7895', '#F9644E',
                '#AF7FEF', '#75D55E', '#6E9EF5', '#FE9418', '#ED60A6',
                '#54B3F0', '#38D786', '#B0DB2E', '#2EA8DB', '#F6B539',
                '#8ABF63', '#E7A061', '#9193EB', '#F9724E', '#7BC963'
            ],

            // 合并线性图表数据
            mergeLineChartData: function(defaultData, chartData) {
                var globalData =
                {
                    chart: {
                        width: 1028,
                        marginRight: 80,
                        style: {
                            fontFamily: '"Microsoft YaHei", Arial, sans-serif'
                        }
                    },
                    labels: {
                        style: {
                            fontFamily: '"Microsoft YaHei", Arial, sans-serif'
                        }
                    },
                    legend: {
                        width: 600,
                        maxHeight: 60,
                        itemStyle: {
                            fontFamily: '"Microsoft YaHei", Arial, sans-serif'
                        }
                    },
                    xAxis: {
                        labels: {
                            maxStaggerLines: 1,
                            x: 40,
                            style: {
                                fontFamily: '"Microsoft YaHei", Arial, sans-serif'
                            }
                        }
                    },
                    yAxis: {
                        labels: {
                            style: {
                                fontFamily: '"Microsoft YaHei", Arial, sans-serif'
                            }
                        }
                    },
                    tooltip: {
                        style: {
                            fontFamily: '"Microsoft YaHei", Arial, sans-serif'
                        }
                    }
                };

                // 计算图例宽度
                var maxSerie = _.max(chartData.series, function(x) {
                    return x.name.length;
                });
                if (maxSerie && maxSerie.name) {
                    globalData.legend.itemWidth = (maxSerie.name.length + 3) * 12;
                }

                var result = $.extend(true, globalData, defaultData, chartData);
                return result;
            },

            formatData: {
                // 没有小数位
                thousands: function (num) {
                    var intNum = parseInt(num, 10);
                    if (isNaN(intNum)) {
                        return num;
                    }
                    return intNum.toFixed(0).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
                },
                //带有两位小数位
                thousands1: function (num) {
                    var floatNum = parseFloat(num);
                    if (floatNum === 0) {
                        return num;
                    }
        
                    if (isNaN(floatNum)) {
                        return num;
                    }
        
                    if (floatNum.toString().indexOf(".") > 0) {
                        return (floatNum.toFixed(2) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
                    } else {
                        return (floatNum.toFixed(0) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
                    }
                }
            },

            initData: function() {
                // 初始化数据
                var promises = [
                    // 项目列表
                    $http.get('/api/index.php?r=qmyx/customer-manage/get-project-list&flag=1')
                ];

                return $q.all(promises).then(function (xhrs) {
                    var i = 0;
                    service.projectList = xhrs[i++].data.data;

                    service.loaded = true;
                });
            },

            getFilters: function () {
                if (service.endDate) {
                    var end = moment(service.endDate);
                    var today = moment().startOf('day').subtract(1);
                    if (end.isAfter(today)) {
                        util.alert('只能查询截止至今天零点之前的数据');
                        return null;
                    }

                    if (service.startDate) {
                        var start = moment(service.startDate);
                        if (start.isAfter(end)) {
                            util.alert('开始日期必须小于或等于结束日期');
                            return null;
                        }
                    }
                }

                service.checkAllowedCycle();

                var filters = {
                    projguids: service.projectIds || [],
                    start_time: service.startDate,
                    end_time: service.endDate
                };

                return filters;
            },

            setDateMode: function(mode) {
                service.dateMode = mode;
                var start, end;
                var today = moment().startOf('day').subtract(1);

                switch (mode) {
                    case 'year':
                        start = moment().startOf('day').subtract(1, 'day').startOf('year');
                        end = moment(start).add(1, 'years').subtract(1);
                        if (end.isAfter(today)) {
                            end = today;
                        }
                        break;
                    
                    case 'quarter':
                        start = moment().startOf('day').subtract(1, 'day').startOf('quarter');
                        end = moment(start).add(1, 'quarters').subtract(1);
                        if (end.isAfter(today)) {
                            end = today;
                        }
                        break;

                    case 'month':
                        start = moment().startOf('day').subtract(1, 'day').startOf('month');
                        end = moment(start).add(1, 'months').subtract(1);
                        if (end.isAfter(today)) {
                            end = today;
                        }
                        break;
                    
                    case 'week':
                        start = moment().startOf('day').subtract(1, 'day').startOf('week');
                        end = moment(start).add(1, 'weeks').subtract(1);
                        if (end.isAfter(today)) {
                            end = today;
                        }
                        break;
                    
                    case 'custom':
                        return;
                }

                if (start) {
                    service.startDate = start.format('YYYY-MM-DD');
                } else {
                    service.startDate = '';
                }
                if (end) {
                    service.endDate = end.format('YYYY-MM-DD');
                } else {
                    service.endDate = '';
                }
            },

            // 检测允许的周期
            checkAllowedCycle: function() {
                service.allowWeekCycle = true;
                service.allowMonthCycle = true;
                if (service.dateMode != 'custom') {
                    service.allowWeekCycle = service.dateMode != 'week' || service.dateMode == 'all';
                    service.allowMonthCycle = service.dateMode != 'week' && service.dateMode != 'month' || service.dateMode == 'all';
                }

                if (service.startDate) {
                    var weekEnd = moment(service.startDate).startOf('week').add(1, 'weeks').subtract(1);
                    var monthEnd = moment(service.startDate).startOf('month').add(1, 'months').subtract(1);
                    var end = service.endDate ? moment(service.endDate) : moment().startOf('day').subtract(1);
                    if (!end.isAfter(weekEnd)) {
                        service.allowWeekCycle = false;
                    }

                    if (!end.isAfter(monthEnd)) {
                        service.allowMonthCycle = false;
                    }
                }
            },

            // 获取有效的周期
            getValidCycle: function (cycle) {
                if (!service.allowWeekCycle) {
                    return '2';
                }
                else if (!service.allowMonthCycle && cycle == '0') {
                    return '1';
                }

                return cycle;
            },


        };

        service.setDateMode('month');

        return service;
    };
    commonModule.factory('baseData', ['$http', '$q', baseDataService]);

    function HeaderController($scope, baseData) {
        $scope.baseData = baseData;
        setTimeout(function () {
            // setTimeout 为了让路由先完成，防止 dom 元素闪动
            baseData.initData();
        }, 50);
    }
    commonModule.controller('HeaderController', ['$scope', 'baseData', HeaderController]);
});